<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>my Blockly</title>
  <link rel="stylesheet" type="text/css" href="blockly.css">
  <link rel="stylesheet" type="text/css" href="../codemirror/lib/codemirror.css">
  <script src="./js/blockly_compressed.js"></script>
  <script src="./js/blocks_compressed.js"></script>
  <script src="./msg/js/en.js"></script>
  <script src="./js/python_compressed.js"></script>
  <script src="./js/define-blocks.js"></script>
  <script src="../codemirror/lib/codemirror.js"></script>
  <script src="../codemirror/mode/python/python.js"></script>
</head>
<body>
<div id="blocklyDiv" style="width: 70%;height: 100%; float: left;"></div>
<div style="width: 30%;height: 100%; float: left;position: relative;">
  <div class="model-header">Python</div>
  <div class="editor-container">
    <div id="editor" style="width: 100%;height: 100%;"></div>
  </div>
</div>
<xml id="toolbox" style="display: none">
  <category name="Logic" colour="%{BKY_LOGIC_HUE}">
    <block type="controls_if"></block>
    <block type="logic_compare"></block>
    <block type="logic_operation"></block>
    <block type="logic_negate"></block>
    <block type="logic_boolean"></block>
    <block type="controls_repeat_ext"></block>
    <block type="string_length"></block>
    <block type="math_change"></block>
  </category>
  <category name="Loops" colour="%{BKY_LOOPS_HUE}">
    <block type="controls_repeat_ext">
      <value name="TIMES">
        <block type="math_number">
          <field name="NUM">10</field>
        </block>
      </value>
    </block>
    <block type="controls_whileUntil"></block>
    <block type="controls_for">
      <field name="VAR">i</field>
      <value name="FROM">
        <block type="math_number">
          <field name="NUM">1</field>
        </block>
      </value>
      <value name="TO">
        <block type="math_number">
          <field name="NUM">10</field>
        </block>
      </value>
      <value name="BY">
        <block type="math_number">
          <field name="NUM">1</field>
        </block>
      </value>
    </block>
  </category>
  <category name="Math" colour="%{BKY_MATH_HUE}">
    <block type="math_number">
      <field name="NUM">123</field>
    </block>
    <block type="math_arithmetic"></block>
    <block type="math_single"></block>
  </category>
  <category name="Text" colour="%{BKY_TEXTS_HUE}">
    <block type="text"></block>
    <block type="text_length"></block>
    <block type="text_print"></block>
  </category>
</xml>

<script>
  window.onload = function () {
    let myXml;
    //定义工作空间
    const demoWorkspace = Blockly.inject('blocklyDiv',// 渲染块儿
      {
        media: './media/',
        maxBlocks: 15,
        toolbox: document.getElementById('toolbox'),//工具栏
        grid:
          {
            spacing: 20,
            length: 3,
            colour: '#ccc',
            snap: true
          },
        trashcan: true
      });

    //工作空间变化监听
    demoWorkspace.addChangeListener(onchange);

    //定义代码编辑器
    window.editor = CodeMirror(document.getElementById("editor"), {
      lineNumbers: true,
      mode: "python",
      value: getPython(),
      lineWrapping: true, // 自动换行
      readOnly: true
    });

    //由于每次切换到blockly的tab，该页面都会刷新，因此需要从缓存中取出blockly的xml
    //获取缓存中的当前激活的menu的path。根据path，从缓存中取出相应的xml编码，转成blockly工作空间
    let blockPath = JSON.parse(localStorage.getItem('curActivedMenu')).path;
    let block = localStorage.getItem(blockPath);
    if (myXml) demoWorkspace.clear();
    if (block) {
      myXml = Blockly.Xml.textToDom(block);
      Blockly.Xml.domToWorkspace(myXml, demoWorkspace);
    }


    function onchange() {
      window.editor.setValue(getPython());
      localStorage.setItem(blockPath, getXml());
      window.parent.postMessage({save: false, xml: getXml(), code: getPython()}, '/');
    }

    // 获取Python代码
    function getPython() {
      return Blockly.Python.workspaceToCode(demoWorkspace);
    }

    function getXml() {
      let xml = Blockly.Xml.workspaceToDom(demoWorkspace);
      return Blockly.Xml.domToText(xml);
    }

    document.addEventListener('keydown', (event) => {
      if (event.keyCode === 83 && event.ctrlKey) {
        event.preventDefault();
        save();
      }
    });

    //保存xml代码
    function save() {
      window.parent.postMessage({save: true, xml: getXml(), code: getPython()}, '/');
    }
  };
</script>

</body>
</html>
